import React, { Component } from "react";
import { connect } from "react-redux";
import "./BackPay.scss";
import { Toast, Button } from "antd-mobile";
import { InterfaceG } from "@config/Config";
import yhTools from "../../../../tools/yh";
import MainLayout from "../../../../component/mainLayout/mainLayout";
import { setRepaymentMoney } from "../../../../Redux/Action/repayment/repaymentMoney";

class BackPay extends Component {
	constructor(props) {
		super(props);
		this.state = {
			passwordObj: [
				{ key: 1, isHasPwd: false, value: "" },
				{ key: 2, isHasPwd: false, value: "" },
				{ key: 3, isHasPwd: false, value: "" },
				{ key: 4, isHasPwd: false, value: "" },
				{ key: 5, isHasPwd: false, value: "" },
				{ key: 6, isHasPwd: false, value: "" }
			],
			keyBoards: [1, 2, 3, 4, 5, 6, 7, 8, 9, "", 0, "<—"],
			count: 0, //记录点击次数
			timeText: "120秒后重发",
			time: 120,
			isCanPay: false,
			fromType: "",
			orgi_trans_no: "" //小辉付使用
		};
		this.timer = null;
		this.isOpen = true;
		this.timer1 = null;
	}

	componentDidMount() {
		let urlParams = this.props.location.state;
		if (urlParams) {
			this.props._setRepaymentMoney(urlParams);
		}
		if (urlParams.fromType == "XHD") {
			//小辉贷
			this.countdown();
		} else {
			//小辉付
			this.countdown();
		}
		this.setState({
			orgi_trans_no: urlParams.orgi_trans_no || "",
			pageParams: urlParams.pageParams,
			fromType: urlParams.fromType
		});
	}

	componentWillUnmount() {
		clearInterval(this.timer);
	}

	/**
	 * 键盘输入密码操作
	 */
	inputPwd(keyvalue) {
		if (keyvalue === "") {
			return false;
		}
		let count = this.state.count;
		if (count >= 6) {
			if (keyvalue == "<—") {
				this.backPwd(count, "");
			} else {
				return false;
			}
			return false;
		}
		if (keyvalue == "<—") {
			if (count == 0) {
				return false;
			}
			this.backPwd(count, "");
		} else {
			this.addPwd(count, keyvalue);
		}
	}

	/**
	 * 点击键盘返回键的操作方法
	 * @param {*} count //记录点击键盘密码的次数
	 * @param {*} inputValue //输入密码的值
	 */
	backPwd(count, inputValue) {
		this.state.passwordObj.forEach(item => {
			if (item.key == this.state.count) {
				item.isHasPwd = false;
				item.value = inputValue;
			}
		});
		count = count - 1;
		const isCanPay = this.isCanPay();
		this.setState({
			isCanPay,
			passwordObj: this.state.passwordObj,
			count
		});
	}

	/**
	 * 点击键盘数字键的操作方法
	 * @param {*} count //记录点击键盘密码的次数
	 * @param {*} inputValue //输入密码的值
	 */
	addPwd(count, inputValue) {
		count = count + 1;
		this.state.passwordObj.forEach(item => {
			if (item.key == count) {
				item.isHasPwd = true;
				item.value = inputValue;
			}
		});
		const isCanPay = this.isCanPay();
		this.setState({
			isCanPay,
			count: count,
			passwordObj: this.state.passwordObj
		});
	}

	//是否可以点击确认还款
	isCanPay() {
		return this.state.passwordObj.every(item => {
			if (item.isHasPwd) {
				return true;
			}
		});
	}

	//点击确认还款按钮
	conmitPay() {
		const { passwordObj, isCanPay } = this.state;
		if (!isCanPay) {
			Toast.info("验证码输入错误", 2);
			return false;
		}
		const _this = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			let pwdString = "";
			passwordObj.map(item => {
				pwdString += item.value;
			});
			if (_this.props.repaymentMoney.fromType == "XHD") {
				//好借
				_this.payConfirm(pwdString);
			} else {
				//小辉付
				_this.payXHFConfirm(pwdString);
			}
		}, 1000);
	}

	getYzm() {
		if (!this.isOpen) {
			return false;
		}

		const _this = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			if (_this.props.repaymentMoney.fromType == "XHD") {
				//好借
				_this.getRepayVeryCode();
			} else {
				//小辉付
				_this.getXHFRepayVeryCode();
			}
		}, 1000);
	}

	//倒计时
	countdown() {
		this.isOpen = false;
		const _this = this;
		let { time } = this.state;

		this.timer = setInterval(() => {
			if (time < 1) {
				clearInterval(_this.timer);
				_this.isOpen = true;
				_this.setState({
					time: 120,
					timeText: "重新发送"
				});
			} else {
				time--;
				_this.setState({
					time,
					timeText: `${time}秒后重发`
				});
			}
		}, 1000);
	}

	//重新获取验证码, 预付代付申请接口
	getRepayVeryCode() {
		let urlParams = this.props.location.state;
		const params = {
			url: "/xhd/loan/prePayment",
			params: {
				repayType: urlParams.repayType,
				cinoArray: urlParams.cinoArray,
				bankCode: urlParams.bankCode
			},
			_alertShow: false
		};
		let _that = this;
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					_that.props._setRepaymentMoney(res.data || {});
					_that.countdown();
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	//重新获取验证码, 预付代付申请接口
	getXHFRepayVeryCode() {
		let urlParams = this.props.location.state;
		const params = {
			url: InterfaceG.xhfRepayment,
			params: {
				...urlParams
			},
			_alertShow: false
		};
		let _that = this;
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					_that.setState({
						orgi_trans_no: res.data.orgi_trans_no
					});
					_that.countdown();
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	//好借确认支付接口
	payConfirm(verifyCode) {
		const params = {
			url: `/xhd/loan/submitPay`,
			params: {
				orgi_trans_no: this.props.repaymentMoney.orgi_trans_no,
				verifyCode
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code == "0") {
					this.props._setRepaymentMoney({ totalLoanFee: null, type: "" });
					this.props.history.push({
						pathname: "/payRet",
						state: { ...res.data, goPath: "xhdHome" }
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	/**
	 * 小辉付还款
	 * @param verifyCode
	 */
	payXHFConfirm(verifyCode) {
		let urlParams = this.props.location.state || {};
		const params = {
			orgi_trans_no: this.state.orgi_trans_no,
			verifyCode: verifyCode,
			billNo: urlParams.billNo,
			amount: urlParams.amount,
			channelNo: urlParams.channelNo,
			preTransNo: urlParams.preTransNo
		};
		this.props.history.push({
			pathname: "/xhfPayRet",
			state: { ...params, goPath: "xhfHomeCredit" }
		});
	}
	handleBack = () => {
		const { fromType } = this.state;
		let goBackPath = "";
		if (fromType === "XHD") {
			goBackPath = `/repaymentMoney/${JSON.stringify(this.state.pageParams)}`;
		} else {
			goBackPath = `/xhfRepaymentPage/${JSON.stringify(this.state.pageParams)}`;
		}
		location.replace(`#${goBackPath}`);
	};
	render() {
		const headerParams = {
			header: {
				title: "认证支付",
				isModal: true
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: "1" // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};
		const { passwordObj, keyBoards, timeText } = this.state;

		return (
			<MainLayout pageParams={headerParams} handleBack={this.handleBack}>
				<div className="backpay">
					<div className="backpay-money">
						<h3>还款金额(元)</h3>
						<p>{this.props.repaymentMoney.totalLoanFee}</p>
					</div>
					<div className="pwd-box">
						<p>本次交易需要短信确认，</p>
						<p>
							校验码已发送至您的手机 {this.props.repaymentMoney.sucessPhoneNo}
						</p>
						<div className="pwd-input-box">
							{passwordObj.map((item, index) => {
								return (
									<div key={index} className="pwd-content">
										<span>{item.value}</span>
									</div>
								);
							})}
						</div>
						<div className="time">
							<span onClick={this.getYzm.bind(this)}>{timeText}</span>
						</div>
						<div className="btn">
							<Button onClick={this.conmitPay.bind(this)} type="primary">
								确认还款
							</Button>
						</div>
						<div className="pwd-keyboard-box">
							{keyBoards.map((item, index) => {
								return (
									<div
										onClick={this.inputPwd.bind(this, item)}
										key={index}
										className="pwd-keyboard-content"
									>
										<span className="pwd_keyboard">{item}</span>
									</div>
								);
							})}
						</div>
					</div>
				</div>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_setRepaymentMoney: options => {
			dispatch(setRepaymentMoney(options));
		}
	};
}

const BackPayPage = connect(mapStateToProps, mapDispatchToProps)(BackPay);
export default BackPayPage;
